package org.jerrymouse.jsa4j.db.kv.derby;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jerrymouse.jsa4j.db.kv.DBManager;

/**
 * 可以作为Provider使用。提供的properties有：
 * <ul>
 * <li>basePath:基础路径</li>
 * </ul>
 * 
 * @author yankai
 * 
 */
public class DerbyDBManager implements DBManager {
	private Map<String, String> properties = new HashMap<String, String>();
	private DBUtil dbUtil;
	@SuppressWarnings("unused")
	private static Log log = LogFactory.getLog(DerbyDB.class);

	@Override
	public DerbyDB getDB() {
		dbUtil = new DBUtil(getUrl());
		return new DerbyDB(dbUtil);
	}

	@Override
	public void setProperties(Map<String, String> properties) {
		this.properties = properties;
	}

	private String getBasePath() {
		if (properties == null) {
			properties = new HashMap<String, String>();
		}
		if (properties.get("basePath") == null) {
			String basePath = System.getProperty("user.home") + "/.jsa4j/db/";
			properties.put("basePath", basePath);
		} else if (properties.get("basePath").startsWith("home:")) {
			String basePath = System.getProperty("user.home")
					+ properties.get("basePath").substring("home:".length());
			properties.put("basePath", basePath);
		}
		return properties.get("basePath");
	}

	private String getUrl() {
		return "jdbc:derby:" + getBasePath() + "derby" + ";create=true";
	}
}
